package pers.cnzdy.tutorial.Chapter7_Data.Section2_SharedPreference;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import pers.cnzdy.tutorial.R;

// 保存和恢复个人信息
public class SharedPreferencesActivity extends AppCompatActivity {
    private String id = "me";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);

        Button btnSave = findViewById(R.id.save_shared_preferences_data);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = getSharedPreferences(id, MODE_PRIVATE).edit();

                editor.putString("昵称", "菜鸟");
                editor.putString("简介", "Android初学者");
                editor.putInt("年龄", 21);
                editor.putBoolean("是否已选课", true);
                editor.commit();
            }
        });

        Button btnRestore = findViewById(R.id.restore_shared_preferences_data);
        btnRestore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences pref = getSharedPreferences(id, MODE_PRIVATE);

                String nickname = pref.getString("昵称", "");
                String briefIntro = pref.getString("简介", "");
                int age = pref.getInt("年龄", 0);
                boolean signUp = pref.getBoolean("是否已选课", false);

                Log.d("SharedPreferences", "昵称： " + nickname +
                        "简介： " + briefIntro + "年龄：" + age + "是否已选课： " + signUp);
            }
        });
    }
}
